package org.bozo.im.service.protocols.xmpp.stanza.util.sasl;

import java.security.NoSuchAlgorithmException;
import java.security.SecureRandom;

import org.bozo.im.service.Constants;
import org.bozo.im.service.protocols.xmpp.XMPPSession;
import org.bozo.im.service.protocols.xmpp.util.namespace.Namespace;

import android.util.Log;

public class MD5Mechanism implements Mechanism {

	public String getName() {
		return "DIGEST-MD5";
	}

	public void toAuthStanza(XMPPSession pSession, StringBuilder pBuilder) {
		// ---------------------------------------------------------------------------------------
		Log.d(Constants.ACTIVITY_TAG, "org.bozo.im.xmpp.util.sasl.MD5Mechanism.toAuthStanza ---------- Authentication through DIGEST-MD5 mechanism");
		// ---------------------------------------------------------------------------------------
		
		pBuilder.append("<auth mechanism='").append(getName()).append("' xmlns='").append(Namespace.SASL.getNamespace()).append("'/>");
		
		byte[] lNonce = new byte[16];
		SecureRandom lRand;
		try {
			lRand = SecureRandom.getInstance("SHA1PRNG");
			lRand.nextBytes(lNonce);
			
			String lConce = new String(lNonce).replace('"', 'A');
			pSession.getConfiguration().putProperty("md5-conce", lConce);
			pSession.getConfiguration().putProperty("md5-nc", 1);
			
		} catch (NoSuchAlgorithmException e) {
			e.printStackTrace();
		}
		
		pSession.getConfiguration().putProperty("sasl-mechanism", getName());
		
	}
}
